﻿using MediatR;
using S.EarTag.Domain.Model;
using S.EarTag.Infrastructure.Repository.Interface.IEarTagRepository;
using S.EarTag.Read.API.Application.MediatorCommand.BodyMeasureCommand;
using S.Common.ApiResult;
using S.Archives.Domain.S.ArchivesModel;
using Newtonsoft.Json;
using S.EarTag.Domain.Dto;
using S.Common.Enums.Archives;
using S.Archives.Domain.S.ArchivesDto;

namespace S.EarTag.Read.API.Application.MediatorCommandHandler.BodyMeasureCommandHandler
{
    public class BodyMeasureListPageCommandHandler : IRequestHandler<BodyMeasureListPageCommand,ApiResult<List<BodyMeasurementDto>>>
    {
        private readonly IBodyMeasureModelRepository _bodyMeasureModelRepository;
        private readonly IConfiguration _configuration;
        public BodyMeasureListPageCommandHandler(IBodyMeasureModelRepository bodyMeasureModelRepository, IConfiguration configuration)
        {
            _bodyMeasureModelRepository = bodyMeasureModelRepository;
            _configuration = configuration;
        }
        /// <summary>
        /// 条件查询+分页显示体尺测量数据
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<ApiResult<List<BodyMeasurementDto>>> Handle(BodyMeasureListPageCommand request, CancellationToken cancellationToken)
        {
            var list = await _bodyMeasureModelRepository.GetAllAsync();

            var i = _configuration["eartagurl"];

            //构造HTTP请求
            HttpClient httpClient = new HttpClient();
            HttpRequestMessage httpRequest = new HttpRequestMessage(HttpMethod.Get, $"{i}/ach/api/SheepFileModel/GetSheepFilesAll?id=3");
            HttpResponseMessage httpResponse = await httpClient.SendAsync(httpRequest);

            //读取响应内容
            string responseContent=await httpResponse.Content.ReadAsStringAsync();

            //反序列化响应内容为 SheepFileModel 的列表
            List<SheepFileDto> sheepFileModels = JsonConvert.DeserializeObject<List<SheepFileDto>>(responseContent);

            //使用Linq进行连接查询
            var query = from a in list
                        join b in sheepFileModels on a.EarTag equals b.EarTag
                        where ((string.IsNullOrEmpty(request.EarTag) || a.EarTag.Contains(request.EarTag)) && 
                        (request.VarietyEnum==0 || b.Variety==(VarietyEnum)request.VarietyEnum) && 
                        (request.Sex==0 || b.Sex==request.Sex))
                        select new BodyMeasurementDto
                        {
                            BodyMeasureId=a.BodyMeasureId,
                            VarietyEnum= b.Variety,
                            Sex= b.Sex,
                            buildingName=b.BuildingName,
                            columnName=b.ColumnName,
                            MeasureDate=a.MeasureDate,
                            birthDate=b.BirthDate,
                            EarTag=a.EarTag,
                            Height=a.Height,
                            BodyLength=a.BodyLength,
                            Chest=a.Chest,
                            Tube=a.Tube,
                            Oschea=a.Oschea,
                            Backfat=a.Backfat,
                            EyeMuscleArea=a.EyeMuscleArea,
                            EyeMuscleWidth=a.EyeMuscleWidth,
                            CreateBy=a.CreateBy,
                            CreateDate=a.CreateDate,
                            UpdateBy=a.UpdateBy,
                            UpdateDate=a.UpdateDate,
                        };
            var query1 = query.ToList();
            ApiResult <List<BodyMeasurementDto>> apiResult = new ApiResult<List<BodyMeasurementDto>>();
            apiResult.Data = query1;
            //总条数、总页数
            apiResult.totalCount = query1.Count();
            apiResult.pageCount = (int)Math.Ceiling((apiResult.totalCount * 1.0) / request.pageSize);
            //分页
            apiResult.Data = query1.Skip((request.pageIndex - 1) * request.pageSize).Take(request.pageSize).ToList();
            return apiResult;
        }
    }
}
